﻿#include "DownloadFileRequest2Private.h"
#include "ZFtpUtils.h"
#include "DownloadFileResponse2Private.h"
#include <QTextCodec>

BEGIN_NAMESPACE_ZFTPNS

DownloadFileRequest2Private::DownloadFileRequest2Private(QObject *parent) :
    ZFtpRequestPrivate(parent),
    q_ptr(NULL)
{

}

int DownloadFileRequest2Private::commandID() const
{
    return ZFtpRequestPrivate::Get;
}

int DownloadFileRequest2Private::doRequest(QSharedPointer<QFtp> ftp, QSharedPointer<ZFtpConfig> cfg)
{
    if (!ftp) return -1;
    else
    {
        ftp->disconnect(this);
        connect(ftp.data(), SIGNAL(commandFinished(int,bool)), SLOT(slotCommandFinished(int,bool)));
    }

    if (cfg)
    {
        // 进行编码转换，防止中文乱码
        QTextCodec *text_codec = cfg->ftpServerTextCodec();

        // QString直接包裹指定编码的数据
        QString coded_ftp_filepath = ZFtpUtils::toTextCodecString(text_codec, m_ftp_filepath);

        if (m_file.isOpen()) m_file.close();
        m_file.setFileName(m_local_savepath);
        if (!m_file.open(QFile::WriteOnly))
        {
            m_task_id = -1;
        }
        else
        {
            m_task_id = ftp->get(coded_ftp_filepath, &m_file);
        }
    }
    else
    {
        m_task_id = ftp->get(m_ftp_filepath, &m_file);
    }

    return m_task_id;
}

QPointer<ZFtpRequest> DownloadFileRequest2Private::publicObject()
{
    return QPointer<ZFtpRequest>(q_ptr);
}

ZFtpResponsePrivate *DownloadFileRequest2Private::createResponse()
{
    return new DownloadFileResponse2Private();
}

void DownloadFileRequest2Private::slotCommandFinished(int id, bool error)
{
    Q_UNUSED(error)

    if (m_task_id != id) return;

    // 置无效
    m_task_id = -1;

    if (m_file.isOpen())
        m_file.close();
}

END_NAMESPACE
